package cfca.paperless.client.servlet.tools;

import java.security.MessageDigest;
import java.util.List;
import cfca.paperless.client.bean.MultiDataBean;

public class ProofHashUtil {
    public static String getProofHashXml(List<MultiDataBean> list) throws Exception {
        StringBuilder proofHashXmlTemp = new StringBuilder("<ProofHashXml>");
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            MultiDataBean multiDataBean = list.get(i);
            byte[] data = multiDataBean.getMultiData();
            if (null != data) {
                String hash = bytes2hex(digest(data));
                proofHashXmlTemp.append("<Proof fileName=\"" + multiDataBean.getFileName() + "\" hash=\"" + hash + "\" type=\"" + multiDataBean.getType()
                        + "\" descr=\"" + multiDataBean.getDescr() + "\"></Proof>");
            }
        }
        proofHashXmlTemp.append("</ProofHashXml>");
        return proofHashXmlTemp.toString();
    }
    private static String bytes2hex(byte[] bytes) {
        String result = "";
        String b = "";
        for (int i = 0; i < bytes.length; i++) {
            b = Integer.toHexString(bytes[i] & 0xFF);
            if (b.length() == 1) {
                b = "0" + b;
            }
            result += b;
        }
        return result.toUpperCase();
    }
    private static byte[] digest(byte[] source) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(source);
        return md.digest();
    }
}
